<?php
require_once('../includes/init.php');
require('../member/session.php');
require('../includes/lib_order.php');
require('../includes/lib_region.php');
require('../includes/cls_crumb.php');
$domain = "https://www.pentalink.com";
function m_mb_convert_encoding($string) {
	if(!is_array($string) && !is_int($string)) {
		return mb_convert_encoding($string, 'UTF-8', 'UTF-8');
	}

	foreach($string as $key => $value) {
		$string[$key] = m_mb_convert_encoding($value);
	}

	return $string;
}
function http_get($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; rv:1.7.3) Gecko/20041001 Firefox/0.10.1");
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_AUTOREFERER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);    
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);

    $content = curl_exec($ch);
    $error = curl_error($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if(empty($error) && $code === 200) return $content;
    else {
	echo "失败";
    }
}

if($_SERVER['REQUEST_METHOD'] == 'POST' && $_POST['act'] == 'post')
{
    $ids = $_POST['ids'];
    $ids =array_filter(explode(",", $ids));
   $sql = "SELECT COUNT(*) FROM `cart` WHERE session_id = '" . $_SESSION[SESSION_PREFIX]['session_id'] . "';";
    if ($db->getOne($sql) <= 0)
    {
        $rs_arr = array(
            'type' => 0,
            'msg'  => '请先选择商品'
        );
        die(json_encode($rs_arr));
    }
	
	$sql = "SELECT * FROM `user_address` WHERE `address_id`='".$_POST['cguid']."';";
	$address = $db->getRow($sql);
	
	$sql = "SELECT * FROM `user_invoice` WHERE `invoice_id`='".$_POST['iguid']."';";
	$invoice = $db->getRow($sql);
	$cart_all_goods = cart_goods($_SESSION[SESSION_PREFIX]['session_id']);

    $cart_goods = [];
    foreach($cart_all_goods as $cart_item){
        if(in_array($cart_item["cart_id"], $ids)){
            $cart_goods[] = $cart_item;
        }
    }
	
	$total = order_fee($cart_goods);
	$order_sn = get_order_sn();
	if($_POST['iguid']=='0')
	{
		$invoice_type = '-1';
	}
	else
	{
		$invoice_type = $invoice['type'];
	}

    if (!$invoice){
        $invoice['invoice_id'] = 0;
    }
	
	$sql = "INSERT INTO `order_info` SET `order_sn`='".$order_sn."',`user_id`='".$_SESSION[SESSION_PREFIX]['user_id']."',".
		     "`order_status`='0',".
		   "`address_id`='".$_POST['cguid']."',`consignee`='".$address['consignee']."',`province`='".$address['province']."',".
		   "`city`='".$address['city']."',`district`='".$address['district']."',`address`='".$address['address']."',".
		   "`tel`='".$address['tel']."',`mobile`='".$address['mobile']."',`email`='".$address['email']."',`invoice_type`='".$invoice_type."',".
		   "`invoice_id`='".$invoice['invoice_id']."',`invoice_company`='".$invoice['company']."',`invoice_address`='".$invoice['address']."',".
		   "`invoice_bank`='".$invoice['bank']."',`invoice_account`='".$invoice['account']."',`invoice_tel`='".$invoice['tel']."',".
		   "`invoice_taxno`='".$invoice['taxno']."',`paymode`='".$_POST['paymode']."',`shipping_fee`='".$total['shipping_fee']."',".
		   "`pay_fee`='0',`product_amount`='".$total['goods_price']."',`add_tm`=NOW();";
	if($db->query($sql))
	{
		$order_id = $db->insert_id();
		foreach($cart_goods as $goods)
		{		
			$sql = "SELECT `is_show` FROM `product` WHERE `product_id`='".$goods['product_id']."';";
			$pshow = $db->getOne($sql);
			$sql = "SELECT * FROM `product_detail` WHERE `pd_id`='".$goods['pd_id']."';";
			$gg = $db->getRow($sql);
            
            $productSku = $gg["sku"];
            $url = "http://101.231.239.50:8083/json.webmaterial/admin_admin8888_0_{$productSku}.html";
            $erpData = http_get($url);
            $erpData = json_decode(m_mb_convert_encoding($erpData), true);
            if(!$erpData["data"][0]["stocks"]){
                $gg['stock'] = 0;
            }else{
                $gg['stock'] = $erpData["data"][0]["stocks"];
            }
			if($pshow=='1' && $gg['is_show']=='1' && $gg['is_del']=='0')
			{
                if($gg['stock'] <= 0){
                    //全是需要采购
                    $sql = "UPDATE `product_detail` SET `stock`=`stock`-".intval($goods['pcount'])." WHERE `pd_id`='".$goods['pd_id']."';";
                    $db->query($sql);
                    
                    $addData = "+ " . $gg["delivery"] . " day";
                    $deliverydate = date("Y-m-d H:i:s", strtotime($addData));
                    $sql = "INSERT INTO `order_detail` SET `deliverydate` = '$deliverydate', `stock_status` = 2, `order_id`='".$order_id."',`product_id`='".$goods['product_id']."',`pd_id`='".$goods['pd_id']."',`supplier_id`='".$gg['supplier_id']."',`brand_id`='".$gg['brand_id']."',`pcount`='".$goods['pcount']."',`pkg`='".$goods['pkg']."',`price`='".$goods['price']."';";
                    $db->query($sql);
                }else if ($gg['stock'] >= $goods["pcount"]){
                    //全是现货
                    $sql = "UPDATE `product_detail` SET `stock`=`stock`-".intval($goods['pcount'])." WHERE `pd_id`='".$goods['pd_id']."';";
                    $db->query($sql);
                    
                    $deliverydate = date("Y-m-d H:i:s", strtotime('+5 day'));
                    $sql = "INSERT INTO `order_detail` SET `deliverydate` = '$deliverydate',  `stock_status` = 1, `order_id`='".$order_id."',`product_id`='".$goods['product_id']."',`pd_id`='".$goods['pd_id']."',`supplier_id`='".$gg['supplier_id']."',`brand_id`='".$gg['brand_id']."',`pcount`='".$goods['pcount']."',`pkg`='".$goods['pkg']."',`price`='".$goods['price']."';";
                    $db->query($sql);
                }else{
                    //部分现货
                    $sql = "UPDATE `product_detail` SET `stock`=`stock`-".intval($goods['pcount'])." WHERE `pd_id`='".$goods['pd_id']."';";
                    $db->query($sql);
                    
                    $deliverydate = date("Y-m-d H:i:s", strtotime('+5 day'));
                    $sql = "INSERT INTO `order_detail` SET `deliverydate` = '$deliverydate', `stock_status` = 1, `order_id`='".$order_id."',`product_id`='".$goods['product_id']."',`pd_id`='".$goods['pd_id']."',`supplier_id`='".$gg['supplier_id']."',`brand_id`='".$gg['brand_id']."',`pcount`='".$gg['stock']."',`pkg`='".$goods['pkg']."',`price`='".$goods['price']."';";
                    $db->query($sql);

                    $addData = "+ " . $gg["delivery"] . " day";
                    $deliverydate = date("Y-m-d H:i:s", strtotime($addData));
                    $sql = "INSERT INTO `order_detail` SET `deliverydate` = '$deliverydate',`stock_status` = 2, `order_id`='".$order_id."',`product_id`='".$goods['product_id']."',`pd_id`='".$goods['pd_id']."',`supplier_id`='".$gg['supplier_id']."',`brand_id`='".$gg['brand_id']."',`pcount`='".((int)$goods['pcount'] - (int)$gg['stock'])."',`pkg`='".$goods['pkg']."',`price`='".$goods['price']."';";
                    $db->query($sql);
                }

			}			
		}
        $ids = "(" . implode(",", $ids) . ")";
		$sql = "DELETE FROM `cart` WHERE `price` > 0 and cart_id in $ids AND `session_id`='".$_SESSION[SESSION_PREFIX]['session_id']."';";
		$db->query($sql);
		$rs_arr = array(
            'type' => 1,
            'msg'  => '提交成功',
            'order_id' => $order_sn
        );
        die(json_encode($rs_arr));
		exit;
	}
	else
	{
        $rs_arr = array(
            'type' => 0,
            'msg'  => '提交失败'
        );
        die(json_encode($rs_arr));
		exit;
	}
}

?>
<?php include('./header.php');?>
<link href="../css/v1/shopcart.css" rel="stylesheet" type="text/css" />
<style>
    .pcsnum {
        font-size: 12px;
    }
    .increase {
        line-height: 12px;
    }
    .reduce{
        line-height: 12px;
    }
    .ksbj_cont a{
        color: white;
    }
    .cut_cont a{
        color: #E90211;
    }
    .add_invoice_btn a:hover{
        color: white;
    }
</style>
<?php
$sql = "SELECT count(*) FROM `cart` WHERE `session_id`='".$_SESSION[SESSION_PREFIX]['session_id']."';";
$cart_sum = $db->getOne($sql);
?>
<style>
    .shouhuoaddr_list .fr span{
        padding-left: 10px;
        cursor: pointer;
        display: inline-block;
        line-height: 1;
        font-size: 14px;
    }
    .address_btn:hover{
        color: #E90211 !important;
    }
</style>
            <!-- 头部搜索框以及导航栏 -->
            <div class="header_div">
                <?php include('./common/search.php');?>
                <?php include('./common/nav.php');?>
            </div>
 
            <!-- 标签 -->
            <div class="post_position">
                <span class="home_span"><a>首页 > </a></span>
                <span><a>订单结算</a></span>
            </div>

            <div class="order_content box">
                <h1 class="tit_h1">提交订单</h1>
                <h2 class="tit_h2 box">收货地址</h2>
                <?php
                $sql = "SELECT * FROM `user_address` WHERE `user_id`='".$_SESSION[SESSION_PREFIX]['user_id']."' order by is_default desc limit 1;";
                $address = $db->getRow($sql);
                $address_str = $address['consignee'].'，'.$address['province_txt'].'，'.$address['city_txt'].'，'.$address['district_txt'].'，'.$address['address'].'，'.$address['mobile'].'，'.$address['tel'];
                ?>
                <div class="select_input box">
                        <h3 class="tit_h3 box">
                            <span class="address_detail" style="padding-right: 20px;">
                                <?php if(!empty($address)): ?>
                                <?php echo $address_str ?>
                                <?php endif; ?>
                            </span>
                            <span style="color: #E90211 !important;cursor: pointer;" onclick="showSelectAddress()">选择</span>

                        </h3>
                </div>
                <?php if(!empty($address)): ?>
                <input class="order_address_id" type="hidden" value="<?php echo $address['address_id']; ?>" />
                <?php else: ?>
                <input class="order_address_id" type="hidden" value="0" />
                <?php endif; ?>
                <h2 class="tit_h2 box" >发货方式</h2>
                <div class="radio_input box" style="margin-bottom: 0;">
                    <input onclick="send_type_now()" type="radio" name="send_type" value="0" checked="true"/>有多少发多少
                    <input onclick="send_type_all()" type="radio" name="send_type" value="1" style="margin-left: 47px" />一起发
                </div>
                <h2 class="tit_h2 box" style="margin-top: 25px;">发票信息</h2>
                <div class="radio_input box" style="margin-bottom: 0;">
                    <input onclick="bukaipiao()" type="radio" name="radio1" value="0" checked="true"/>不开票
                    <input onclick="kaipiao()" type="radio" name="radio1" value="1" style="margin-left: 47px" />开票
                </div>
                
                <div class="invoice_content box" style="min-height: 20px;">
                    <ul class="invoice_list box" style="display: none;">
                    <?php
                    $sql = "SELECT * FROM `user_invoice` WHERE `user_id`='".$_SESSION[SESSION_PREFIX]['user_id']."' ORDER BY `is_default` DESC,`company`,`invoice_id` DESC;";
                    $invoice_list = $db->getAll($sql);
                    if(!empty($invoice_list)):
                    foreach($invoice_list as $key => $invoice):
                    ?>
                        <li>
                            <div class="fl">
                                <input <?php if($invoice['is_default']=='1'):?> id="default_fapiao" <?php endif;?> type="radio" name="fapiao_list_item" onclick="chooseInvoice(<?php echo $invoice['invoice_id'];?>)">
                                <span><?php echo $invoice['company'];?></span>
                                <span><?php if($invoice['type']=='0') echo "普通发票"; else echo "增值税发票";?></span>
                                <?php if($invoice['is_default']=='1'):?>
                                    <span style="font-size: 12px;color: #E90211 !important;">（默认发票）</span>
                                <?php endif;?>
                            </div>
                            <div class="fr">
                                <?php if($invoice['is_default']=='0'):?>
                                    <span class="e9" onclick="setDefault(<?php echo $invoice['invoice_id'];?>)">设为默认</span>
                                <?php endif;?>
                                <span class="del" onclick="deleteInvoice(<?php echo $invoice['invoice_id'];?>)">删除</span>
                                <span onclick="editInvoice(<?php echo $invoice['invoice_id'];?>)">编辑</span>
                            </div>
                        </li>
                    <?php
                    endforeach;
                    ?>
                    <?php else: ?>
                        <div style="height: 80pxpx;line-height: 80px;">暂无发票</div>
                    <?php
                    endif;
                    ?>
                    </ul>
                    <div class="add_invoice_btn box" style="display: none;">
                        <a style="cursor: pointer;" onclick="showAddInvoice()">添加发票抬头</a>
                    </div>
                </div>

                <h2 class="tit_h2 box">商品明细</h2>
                <table class="table table-condensed">
                    <thead>
                        <tr>
                            <th>商品型号</th>
                            <th>规格</th>
                            <th>包装</th>
                            <th>交货类型</th>
                            <th>单价</th>
                            <th>数量</th>
                            <th>小计</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>

                        <?php
                        $tj_cate = array();//下面的推荐分类关联
                        $cart_all_list = cart_goods($_SESSION[SESSION_PREFIX]['session_id']);
                        $cart_list = [];
                        $ids = $_GET['ids'];
                        $ids = explode(",", $ids);
                        foreach($cart_all_list as $cart_item){
                            if(in_array($cart_item["cart_id"], $ids)){
                                $cart_list[] = $cart_item;
                            }
                        }

                        $total = order_fee($cart_list);
                        $total_num = 0;//总的数量
                        if(!empty($cart_list)):
                        foreach($cart_list as $key => $cart):
                            $sql = "SELECT * FROM `product` WHERE `product_id`='".$cart['product_id']."';";
                            $product = $db->getRow($sql);
                            //图片
                            //$sql = "SELECT * FROM `product_pic` WHERE `product_id`='".$product['product_id']."' LIMIT 1;";
                            $sql = "SELECT *,if(`sort_order` > '0',1,0) AS `is_order` FROM `product_pic` WHERE `ftype`=1 AND `product_id`='".$product['product_id']."' ORDER BY `is_order` DESC, `sort_order` LIMIT 1;";
                            //echo $sql;
                            $pic = $db->getRow($sql);
                            //规格信息
                            $sql = "SELECT * FROM `product_detail` WHERE `pd_id`='".$cart['pd_id']."';";
                            $gg = $db->getRow($sql);
                            //$gg['stock'] 库存
                            //$cart['pcount'] 
                            
                            $decimals = $product['bigcate_id']=='1'?4:2;
                            
                            $tj_cate[] = $product['cate_id'];
                            $cate_arr = explode(',', $product['cate_ids']);
                            $cateId = $cate_arr[0];
                        ?>

                            <tr class="pid_<?php echo $cart['pd_id'];?>"  pid="<?php echo $cart['pd_id'];?>">
                                <td>
                                    <a href="./proDetail.php?id=<?php echo $product['product_id'];?>&cate_id=<?php echo $cateId;?>">
                                        <div class="td_img"><img src="<?php echo $domain; ?>/upload<?php echo $pic['pic100'];?>" alt="<?php echo $product['title'];?>"></div>
                                        <div class="td_p">
                                            <p class="p1"><?php echo $product['title'];?></p>
                                            <p>
                                                <?php echo $gg['sku'];//yjt_sku($gg['pd_id']);?><br />
                                                <?php if($gg['brand_id']){?>品牌：<?php echo $cfg_brand[$gg['brand_id']];?><?php }?>
                                                <?php if($gg['is_stocklast']=='1'):?>
                                                <br />库存：<?php echo $gg['stock'];?>
                                                <br /><span class="all-kinds-mark clearance-end">售完即止</span>
                                                <?php endif;?>
                                                </div>
                                                <?php if($gg['is_stocklast']=='1'):?>
                                                <b class="goods-mark goods-mark-clearance goods-mark-imglist">清仓</b>
                                                <?php endif;?>
                                            </p>
                                        </div>
                                    </a>
                                </td>
                                <td><?php echo $gg['xy_value'];?></td>
                                <td>
                                    包装：<?php echo $gg['pkg'];?>个/包<br />
                                </td>
                                <td id="ls_<?php echo $gg['pd_id'];?>"><?php if($gg['stock'] >= $cart['pcount']) echo "现货"; else echo "部分现货";?></td>
                                <td  class="e9 bold">
                                    <span  id="lp_<?php echo $gg['pd_id'];?>">
                                        <?php echo price_format($cart['price'], true, $decimals);?>
                                    </span>
                                </td> 
                                <td>
                                    <a href="javascript:void(0);" class="reduce" onclick="ShopcartUpdateNumber(<?php echo $gg['pd_id'];?>,-1);">-</a>
                                    <input type="text" id="lq_<?php echo $gg['pd_id'];?>" class="pcsnum" pkg="<?php echo $gg['pkg'];?>" value="<?php echo $cart['pcount'];?>" cvalue="<?php echo $cart['pcount'];?>" stock="<?php echo $gg['stock'];?>" onchange="ShopcartUpdateNumber(<?php echo $gg['pd_id'];?>,0);" />
                                    <a href="javascript:void(0);" class="increase" onclick="ShopcartUpdateNumber(<?php echo $gg['pd_id'];?>,1);">+</a>          
                                </td>
                                <td  class="e9 bold">￥
                                    <span id="lt_<?php echo $gg['pd_id'];?>">
                                        <?php echo $cart['price']*$cart['pcount'];?>
                                    </span>
                                </td> 
                                <td style="cursor: pointer;" class="remove" onclick="ShopcartDeleteCurrent(<?php echo $gg['pd_id'];?>);">删除</td>
                            </tr>
                        <?php
                        $total_num += $cart['pcount'];
                        endforeach;
                        endif;
                        ?>
                        
                    </tbody>
                </table>

                <!-- <div class="order_content_notes box"> -->
                    <!-- <input class="chek_input" type="checkbox"> -->
                    <!-- <p>您当前结算货物中存在需要额外采购的商品，请问您是否愿意接受基于交期的等待。如您接受条款，我们将在货物到货后第一时间为您安排发货，如无法接受条款，请删除相关的商品重新进行购买。<span class="e9">点击去除击额外采购商品</span></p> -->
                <!-- </div> -->

                <div class="order_price_detail box">
                    <ul>
                        <li><p style="font-size: 14px;">订单总额满500元免运费，不满500元的需额外支付30元运费。</p></li>
                        <li><p>折扣：<span class="e9">-￥<span class="zhekou"><?php echo $total['discount'];?></span></span></p></li>
                        <li><p>运费：<span  class="e9">+￥<span class="yunfei"><?php echo $total['shipping_fee'];?></span></span></p></li>
                        <li><p>商品总计：<span  class="e9">￥<span class="good_price"><?php echo $total['goods_price'];?></span></span></p></li>
                    </ul>
                </div>
                <div>
                    
                </div>

                <div class="order_commit box">
                    <p>订单总计：<span class="e9">￥<span class="all_price"><?php echo $total['total_fee'];?></span></span></p>
                    <a class="commit_btn" onclick="createOrder()">提交下单</a>
                </div>

                <div class="order_illustrate box">
                    <p class="e9">说明：</p>
                    <p>1、该报价单须遵循本站”销售条款”。</p>
                    <p>2、开票时运费服务费摊入单价。</p>
                    <p>3、所有单价均不含税，并以人民币交易。</p>
                    <p>4、付款方式:收到100%全额货款后订单生效。</p>
                    <p>5、交货期:滚动库存随时变动，具体交期于下订单时重新确认。</p>
                    <p>6、请以包装数量的整数倍订货。</p>
                    <p>7、订单总价会根据实际物流运输、原材料波动、多个供货商等原因略有变动。</p>
                    <p>8、提交订单后，工作人员会尽快与您确认。</p>  
                </div>

            </div>


        <!-- 新增地址弹框 -->
        <div class="newaddr_alert_block" style="z-index: 99999;">
            <input class="address_id" type="hidden" value="0" />
            <div class="newaddr_alert_content transform box">
                <div class="newaddr_alert_close" onclick="hideAddAddress()"><img src="../img/ico_close.png" alt="关闭"></div>
                <div class="title">新增收货地址</div>
                <div class="newaddr_item">
                    <div class="tt tt_act box ">收货人：</div>
                    <div class="input_block">
                        <input type="text" class="newaddr_user box addr_user_name">
                    </div>
                </div>
                <div class="newaddr_item">
                    <div class="tt tt_act box">所在地区：</div>
                    <div class="input_block">
                        <select class="select box" name="cprovince" id="cprovince" onchange="getCity();">
                            <option value="0">请选择</option>
                            <?php
                                $province_list = region_list('1');
                                if(!empty($province_list)):
                                foreach($province_list as $pk => $province):
                            ?>
                            <option value="<?php echo $province['region_id']?>"><?php echo $province['fc']?><?php echo $province['region_name']?></option>
                            <?php
                                endforeach;
                                endif;
                            ?>
                        </select>
                        <select class="select box" id="ccity" name="ccity"  onchange="getVilliage();">
                            <option value="0">请选择</option>
                        </select>
                        <select class="select box" id="cvilliage" name="cvilliage">
                            <option value="0">请选择</option>
                        </select>
                    </div>
                </div>
                <div class="newaddr_item">
                    <div class="tt tt_act box ">详细地址：</div>
                    <div class="input_block">
                        <input type="text" class="newaddr_user box address_info">
                    </div>
                </div>
                <div class="newaddr_item">
                    <div class="tt tt_act box ">手机号码：</div>
                    <div class="input_block">
                        <input type="text" class="newaddr_number box addr_mobile">
                        <p>用于接收发货通知短信</p>
                    </div>
                </div>
                <div class="newaddr_item">
                    <div class="tt tt_act box ">电话号码：</div>
                    <div class="input_block">
                        <input type="text" class="newaddr_number box tel">
                        <p>用于送货前确认</p>
                    </div>
                </div>
                <div class="init_moren_radio">
                    <input type="checkbox" class="isDefault" />
                    <span class="e9">设为默认</span>
                </div>
                <div class="newaddr_alert_btns">
                    <button class="save" onclick="saveAddress()">保存</button>
                    <button class="qx" onclick="hideAddAddress()">取消</button>
                </div>
            </div>

        </div>

        <!-- 收货地址列表弹框 -->
        <div class="shouhuoaddr_alert_block" style="display: none;">
            <div class="shouhuoaddr_alert_content transform box">
                <div class="shouhuoaddr_alert_close" onclick="hideSelectAddress()"><img src="../img/ico_close.png" alt="关闭"></div>
                <div class="title">收货地址</div>
                <div class="address_list_content" style="max-height: 500px;overflow: scroll;min-height: 100px;width: 714px;">
                    <?php
                    $sql = "SELECT * FROM `user_address` WHERE `user_id`='".$_SESSION[SESSION_PREFIX]['user_id']."';";
                    $address_list = $db->getAll($sql);
                    if(!empty($address_list)):
                    foreach($address_list as $key => $list):
                    ?>
                        <div class="shouhuoaddr_list box">
                            <div class="tt">
                                <?php echo $list['consignee']; ?>
                                <span class="e9" style="font-size: 14px;">
                                    <?php if($list['is_default']=='1'):?>（默认地址）<?php endif;?>
                                </span>
                                <div class="fr">
                                    <?php if($list['is_default']!='1'):?>
                                    <span class="e9" onclick="SetAddressDefault(<?php echo $list['address_id']; ?>)">设为默认</span>
                                    <?php endif;?>
                                    <span class="address_btn" onclick="DelAddress(<?php echo $list['address_id']; ?>)">删除</span>
                                    <span class="address_btn" onclick="EditAddress(<?php echo $list['address_id']; ?>)">编辑</span>
                                    <span class="address_btn" onclick="SelectAddress(<?php echo $list['address_id']; ?>)">
                                    <input type="radio" name="test" style="position: relative;top: 2px;">
                                    选择</span>
                                </div>
                            </div>
                            <ul>
                                <li><span>收货人：</span><span class="ellipsis"><?php echo $list['consignee']; ?></span></li>
                                <li><span>手机：</span><span class="ellipsis"><?php echo $list['mobile']; ?></span></li>
                                <li style="width: 100%"><span>固定电话：</span><span class="ellipsis"><?php echo $list['tel']; ?></span></li>
                                <li style="width: 100%"><span>详细地址：</span><span class="ellipsis"><?php echo $list['province_txt']; ?>  <?php echo $list['city_txt']; ?> <?php echo $list['district_txt']; ?> <?php echo $list['address']; ?> </span></li>
                            </ul>
                        </div>
                    <?php
                    endforeach;
                    endif;
                    ?>
                </div>
                <div class="alert_addaddr_btn box" onclick="showAddAddress()">新增收货地址</div>
            </div>

        </div>

           <!-- 发票弹框 -->
           <div class="add_invoice_alert_block" style="display: none;">
            <div class="add_invoice_alert_content transform box">
                <div class="add_invoice_alert_close" onclick="hideAddInvoice()"><img src="../img/ico_close.png" alt="关闭"></div>
                <input type="hidden" class="invoice_id" value="0">
                <input type="hidden" class="i_optype" value="0">
                <div class="add_invoice_content box">
                    <p>新增发票信息：（单位名称请以工商局注册资料为准）</p>
                    <ul>
                        <li>
                            <span class="fl">发票类型：</span>
                            <input class="input_radio itype1" onclick="selectInvoiceType(0)" checked="true" type="radio" name="itype" value="0" />
                            <label>普通发票</label>
                            <input class="input_radio itype2" onclick="selectInvoiceType(1)" type="radio" name="itype" value="1" style="margin-left: 47px"/>
                            <label>增值发票</label>
                        </li>

                        <li class="add_piao_li">
                            <div class="add_piao_item">
                                <div class="tt tt_act box ">公司名称：</div>
                                <div class="input_block">
                                    <input type="text" class="newaddr_user box CompanyName">
                                    <p style="display: none;">请填写公司名称</p>
                                </div>
                            </div>
                            <div class="add_piao_item">
                                <div class="tt tt_act box">税号：</div>
                                <div class="input_block">
                                    <input type="text" class="newaddr_user box TaxNo">
                                    <p style="display: none;">请填写税号</p>
                                </div>
                            </div>
                            <div class="add_piao_item">
                                <div class="tt tt_act box ">地址：</div>
                                <div class="input_block">
                                    <input type="text" class="newaddr_user box Address">
                                </div>
                            </div>
                            <div class="add_piao_item">
                                <div class="tt tt_act box ">电话：</div>
                                <div class="input_block">
                                    <input type="text" class="newaddr_user box Telephone">
                                </div>
                            </div>
                            <div class="add_piao_item">
                                <div class="tt tt_act box ">开户行：</div>
                                <div class="input_block">
                                    <input type="text" class="newaddr_user box OpenBank">
                                    <p style="display: none;">请填写开户行</p>
                                </div>
                            </div>
                            <div class="add_piao_item">
                                <div class="tt tt_act box ">账号：</div>
                                <div class="input_block">
                                    <input type="text" class="newaddr_user box BankAccount">
                                    <p style="display: none;">请填写账号</p>
                                </div>
                            </div>
                            <p class="tip_p box">注意：有效增值税发票开票资质仅为一个。需要在会员中心上传增票资质。</p>
                            <div class="moren"><input type="checkbox" class="invoice_default">设为默认开票资料</div>
                        </li>
                       
                        <li class="general_invoice">
                            <span class="fl">发票抬头：</span>
                            <input class="input_radio iptype1" onclick="selectInvoiceFrom(0)" checked="true" type="radio" name="iptype" value="0" />
                            <label for="geren">个人</label>
                            <input class="input_radio iptype2" onclick="selectInvoiceFrom(1)" type="radio" name="iptype"  value="1" style="margin-left: 47px"/>
                            <label for="gongsi" >公司</label>
                            <input type="text" class="gongsi_input icompany" />
                        </li>
                    </ul>
                    <div class="btns">
                        <a class="save" onclick="saveInvoice()">保存</a>
                        <a class="qx" onclick="hideAddInvoice()">取消</a>
                    </div>
                </div>
            </div>
        </div>



<?php include('./footer.php');?>
<script>
function chooseInvoice(id){
    $(".invoice_id").val(id)
}
var canSub = 1
function createOrder(){
    if(canSub != 1) {
        console.log("请勿重复提交")
        return
    }
    if($(".good_price").text() == 0){
        alert("金额为0，请选择商品");
        return
    }
    if($(".order_address_id").val() == 0){
        alert("请指定收货人信息！");
        return
    }
    canSub = 0
    $.post("./confirm.php", {
        act: "post",
        cguid: $(".order_address_id").val(),
        iguid: $(".invoice_id").val(),
        ids: "<?php echo $_GET["ids"]; ?>",
        paymode: 0
    }, function(data){
        var res = JSON.parse(data)
        if (res.type == 1){
            location.href = "./order.php?id=" + res.order_id
        }else{
            canSub = 1
            alert(res.msg)
        }
    })
}

//删除
function ShopcartDeleteCurrent(pid) {
    var cfn = confirm("您确定要删除当前商品吗?");
    if (!cfn) {
        return false;
    }
    $.post("/ajax/cart.php", { "act":'DelCurrent', "pid": pid }, function(data, state) {
		if(data.type == '1')
		{
			//删除页面上的元素
            $(".pid_" + pid).remove();

			//更新单据金额
			$(".cart_sum").text(data.pnum);//总数量
			$(".good_price").text(data.pta);//商品总金额
			$(".zhekou").text(data.pda);//折扣
            
            $(".yunfei").text(data.scpf);//运费
            $(".all_price").text(data.scpot);//总金额

			return true;
		}
		else if(data.type == '2')
		{
			//刷新页面显示购物车为空。
			window.location = './cart.php';
		}
		else
		{
			return false;
		}
	});
}

//更新购物车产品数量
function ShopcartUpdateNumber(pid, ptype) {
    var lp = "#lp_" + pid;//商品单价
    var lq = "#lq_" + pid;//商品购买数量
    var ls = "#ls_" + pid;//库存
    var lt = "#lt_" + pid;//小计
    var txt = document.getElementById("lq_" + pid);

    var pkg = $(lq).attr("pkg");
    var value = $(lq).attr("value");
    var cvalue = $(lq).attr("cvalue");//原来的值
    var stock = $(lq).attr("stock");

    var regexp = /^[0-9]{1,10}$/;  //验证数字
    if (!value.match(regexp)) {
        alert("数量输入错误！");
        txt.focus();
        return false;
    }
    if (value % pkg != 0) {
        alert("请按包装量的倍数购买！");		
        txt.focus();
        return false;
    }

    pkg = parseInt(pkg, 10);
    value = parseInt(value, 10);
    cvalue = parseInt(cvalue, 10);
    stock = parseInt(stock, 10);
    
    if (ptype == 0) {//update
        if (value == cvalue) return false;//nochange return
    }
    switch (ptype) {
        case -1: //-
            value = value - pkg;
            break;
        case 0: //update
            
            break;
        case 1: //+
            value = value + pkg;
            break;
    }

    if (value < 0) value = 0;
    if (value == 0) {
        alert('数量不能为0，需要删除该产品，请点击删除！');
		return false;
    }

    $.post("/ajax/cart.php", { "act": "ShopcartUpdateNumber", "pid": pid, "pcount": value, "stock": stock, ids: "<?php echo $_GET["ids"]; ?>" }, function(data) {
		if(data.type == '1')
		{
			$(lp).text("￥" + data.price);//单品价格
            $(lt).text(data.ltotal);//单品价格合计
            //$(lq).val(value);//数量
			$(lq).val(data.pcount);//数量采用回调的数量，防止清仓的超过库存量
            $(lq).attr("cvalue", value); //备份数量
            $(ls).text(data.lstock); //库存情况

			$(".good_price").text(data.goods_price);//商品总金额
			$(".zhekou").text(data.discount);//折扣
            
            $(".yunfei").text(data.shipping_fee);//运费
            $(".all_price").text(data.total_fee);//总金额
		}
		else
		{
			alert(data.msg);
			return false;
		}
	});
}
    

    function getInvoiceList(){
        $.post("../ajax/address.php", {act: "InvoiceList"}, function(data){
            var list = JSON.parse(data)
            var str = ""
            for (const key in list.data) {
                str += '<li>'
                str += '<div class="fl">'

                if (list.data[key].is_default == 1){
                    str += '<input id="default_fapiao" onclick="chooseInvoice('+ list.data[key].invoice_id +')" type="radio">'
                }else{
                    str += '<input onclick="chooseInvoice('+ list.data[key].invoice_id +')" type="radio">'
                }

                str += '<span>' + list.data[key].company +'</span>'
                if (list.data[key].type == 0){
                    str += '<span>普通发票</span>'
                }else{
                    str += '<span>增值税发票</span>'
                }
                if (list.data[key].is_default == 1){
                    str += '<span style="font-size: 12px;color: #E90211 !important;">（默认发票）</span>'
                }
                str += '</div>'
                str += '<div class="fr">'

                if (list.data[key].is_default == 0){
                    str += '<span class="e9" onclick="setDefault('+ list.data[key].invoice_id +')">设为默认</span>'
                }
                
                str += '<span class="del" onclick="deleteInvoice('+ list.data[key].invoice_id +')">删除</span>'
                str += '<span onclick="editInvoice('+ list.data[key].invoice_id +')">编辑</span>'
                str += '</div>'
                str += '</li>'
            }
            $(".invoice_list").html(str)
        })
    }
    function editInvoice(id){
        $.post("../ajax/address.php", {act: "InvoiceEdit", id: id}, function(data){
            $(".i_optype").val(1)
            if(data.type == 1){
                $(".add_invoice_alert_block").show()
                $(".invoice_id").val(id)
                if(data.invoice.type == 1){
                    $(".itype2").attr("checked", true)
                    $(".general_invoice").hide()
                    $(".add_piao_li").show()

                    $(".CompanyName").val(data.invoice.company)
                    $(".TaxNo").val(data.invoice.taxno)
                    $(".Address").val(data.invoice.address)
                    $(".Telephone").val(data.invoice.tel)
                    $(".OpenBank").val(data.invoice.bank)
                    $(".BankAccount").val(data.invoice.account)
                    
                    if(data.invoice.is_default == 1){
                        $(".invoice_default").attr("checked", true)
                    }
                }else{
                    $(".itype1").attr("checked", true)
                    $(".general_invoice").show()
                    $(".add_piao_li").hide()
                }

                if (data.invoice.company == "个人"){
                    $(".iptype1").attr("checked", true)
                }else{
                    $(".iptype2").attr("checked", true)
                    $(".icompany").show()
                    $(".icompany").val(data.invoice.company)
                }
            }
        })
    }
    function setDefault(id){
        $.post("../ajax/address.php", {act: "InvoiceSetDefault", id: id}, function(data){
            getInvoiceList()
        })
    }
    function deleteInvoice(id){
        $.post("../ajax/address.php", {act: "InvoiceDelete", id: id}, function(data){
            getInvoiceList()
        })
    }
    function saveInvoice(){
        var act = "InvoiceUpdate"
        var i_optype = $(".i_optype").val()
        var id = $(".invoice_id").val()
        var itype = $("input[name='itype']:checked").val()
        var iptype = $("input[name='iptype']:checked").val()
        var icompany = $(".icompany").val()
        var CompanyName = $(".CompanyName").val()
        var TaxNo = $(".TaxNo").val()
        var Address = $(".Address").val()
        var Telephone = $(".Telephone").val()
        var OpenBank = $(".OpenBank").val()
        var BankAccount = $(".BankAccount").val()
        var IsDefault = $(".invoice_default").attr("checked") == "checked" ? 1 : 0
        $.post("../ajax/address.php", {
            act: act,
            i_optype: i_optype,
            id: id,
            itype: itype,
            iptype: iptype,
            icompany: icompany,
            CompanyName: CompanyName,
            TaxNo: TaxNo,
            Address: Address,
            Telephone: Telephone,
            OpenBank: OpenBank,
            BankAccount: BankAccount,
            IsDefault: IsDefault,
        }, function(data){
            if(data.type != 1){
                alert(data.msg)
                return
            }
            getInvoiceList()
            $(".add_invoice_alert_block").hide()
        })
    }
    function selectInvoiceType(type){
        if(type == 0){
            $(".add_piao_li").hide()
            $(".general_invoice").show()
        }else{
            $(".add_piao_li").show()
            $(".general_invoice").hide()
        }
    }
    function selectInvoiceFrom(type){
        if(type == 0){
            $(".gongsi_input").hide()
        }else{
            $(".gongsi_input").show()
        }
    }
    function showAddInvoice(){
        $(".invoice_id").val(0)
        $(".i_optype").val(0)
        $(".add_invoice_alert_block").show()
    }
    function hideAddInvoice(){
        $(".add_invoice_alert_block").hide()
    }
    function kaipiao() {
        $(".invoice_list").show()
        $(".add_invoice_btn").show()
        $("#default_fapiao").attr("checked", true)
    }
    function bukaipiao() {
        $(".invoice_list").hide()
        $(".add_invoice_btn").hide()
        $(".default_fapiao").attr("checked", false)
    }

    function saveAddress() {
        var addressId = $(".address_id").val();
        var userName = $(".addr_user_name").val();
        var cprovince = $("#cprovince").val();
        var ccity = $("#ccity").val();
        var cvilliage = $("#cvilliage").val();
        var address_info = $(".address_info").val()
        var mobile = $(".addr_mobile").val();
        var tel = $(".tel").val()
        var isDefaultAddress = $(".isDefault").attr("checked") == "checked" ? 1 : 0

        if (userName == ""){
            alert("请输入收货人")
            return
        }
        if (cprovince == 0 || ccity == 0 || cvilliage == 0){
            alert("请选择所在地区")
            return
        }
        if (address_info == ""){
            alert("请输入详细地址")
            return
        }
        if (mobile == ""){
            alert("请输入手机号")
            return
        }
        if (tel == ""){
            alert("请输入电话号码")
            return
        }

        var regexp = /^([0-9-]{7,20})$/; //验证号码
        if (!mobile.match(regexp)) {
            alert("请输入正确格式的手机号")
            return
        }
        if (!tel.match(regexp)) {
            alert("请输入正确格式的电话号码")
            return
        }

        $.post("../ajax/address.php", {
            id:addressId,
            userName: userName,
            cprovince:cprovince,
            ccity:ccity,
            cvilliage:cvilliage,
            address_info:address_info,
            mobile:mobile,
            tel:tel,
            isDefaultAddress:isDefaultAddress,
        }, function(data){
            var res = JSON.parse(data)
            GetAddressList();
            hideAddAddress();
        })
    }

    function GetAddressList(){
        $.post("../ajax/address.php", {
            act: "GetAddressList",
        }, function(data){
            var res = JSON.parse(data)
            if(res.code == 200){
                var str = ""
                for (const key in res.data) {
                    console.log(key, res.data[key])
                    str += '<div class="shouhuoaddr_list box"><div class="tt">'
                    str += res.data[key].consignee
                    str += '<span class="e9" style="font-size: 14px;">'
                    if (res.data[key].is_default == 1){
                        str += "（默认地址）"
                    }
                    str += '</span>'
                    str += '<div class="fr">'
                    if (res.data[key].is_default != 1){
                        str += '<span class="e9" onclick="SetAddressDefault('+ res.data[key].address_id +')">设为默认</span>'
                    }
                    str += '<span class="address_btn" onclick="DelAddress('+ res.data[key].address_id +')">删除</span>'
                    str += '<span class="address_btn" onclick="EditAddress('+ res.data[key].address_id +')">编辑</span>'
                    str += '<span class="address_btn" onclick="SelectAddress('+ res.data[key].address_id +')"><input type="radio" name="test" style="position: relative;top: 2px;">选择</span>'
                    str += '</div>'
                    str += '</div>'
                    str += '<ul>'

                    str += '<li><span>收货人：</span><span class="ellipsis">'+res.data[key].consignee+'</span></li>'
                    str += '<li><span>手机：</span><span class="ellipsis">'+res.data[key].mobile+'</span></li>'
                    str += '<li style="width: 100%"><span>固定电话：</span><span class="ellipsis">'+res.data[key].tel+'</span></li>'
                    str += '<li style="width: 100%"><span>详细地址：</span><span class="ellipsis"> ' + res.data[key].province_txt + res.data[key].city_txt + res.data[key].district_txt + res.data[key].address +'</span></li>'
                    str += '</ul>'
                    str += '</div>'
                }
                $(".address_list_content").html(str)
            }
        })
    }

    function SelectAddress(id){
        $.post("../ajax/address.php", {
            act: "SelectAddress",
            id: id
        }, function(data){
            var detail = JSON.parse(data)
            $(".address_detail").text(detail.data.str)
            $(".order_address_id").val(detail.data.address_id)
            $(".shouhuoaddr_alert_block").hide()
        })
    }

    function EditAddress(id){
        $.post("../ajax/address.php", {
            act: "SelectAddress",
            id: id
        }, function(data){
            var detail = JSON.parse(data)
            $(".address_id").val(id)
            $(".addr_user_name").val(detail.data.consignee)
            $(".address_info").val(detail.data.address)
            $(".addr_mobile").val(detail.data.mobile)
            $(".tel").val(detail.data.tel)
            if(detail.data.is_default == 1){
                $(".isDefault").attr("checked", true)
            }
            $("#cprovince").val(detail.data.province);
            $("#ccity").html(detail.city)
            $("#cvilliage").html(detail.district)
            $(".newaddr_alert_block").show()
        })
    }


    function DelAddress(id){
        $.post("../ajax/address.php", {
            act: "DelAddress",
            id: id
        }, function(data){
            GetAddressList();
            hideAddAddress();

            if (id == $(".order_address_id").val()){
                $(".address_detail").text("")
                $(".order_address_id").val(0)
            }
        })
    }

    function SetAddressDefault(id){
        $.post("../ajax/address.php", {
            act: "SetDefault",
            id: id
        }, function(data){
            GetAddressList();
        })
    }

    function showSelectAddress(){
        $(".shouhuoaddr_alert_block").show()
    }
    function hideSelectAddress(){
        $(".shouhuoaddr_alert_block").hide()
    }
    function showAddAddress(){
        $(".address_id").val(0)
        $(".newaddr_alert_block").show()
    }
    function hideAddAddress(){
        $(".address_id").val(0)
        $(".addr_user_name").val("")
        $(".address_info").val("")
        $(".addr_mobile").val("")
        $(".tel").val("")
        $(".isDefault").attr("checked", false)
        $("#cprovince").val(0);
        $("#ccity").html('<option value="0">请选择</option>')
        $("#cvilliage").html('<option value="0">请选择</option>')
        $(".newaddr_alert_block").hide()
    }

    function getCity()
    {
        $.get("/ajax/city.php?act=getcity&" + "pid="+$('#cprovince').val(), {}, function(e){
            var city = JSON.parse(e)
            var str = '<option value="0">请选择</option>'
            $("#cvilliage").html(str)
            for (const key in city) {
                str += "<option value="+ key +"> " + city[key] +"</option>";
            }
            $("#ccity").html(str)
        })
    }
    function getVilliage()
    {
        $.get("/ajax/city.php?act=getcity&" + "pid="+$('#ccity').val(), {}, function(e){
            var city = JSON.parse(e)
            var str = '<option value="0">请选择</option>'
            for (const key in city) {
                str += "<option value="+ key +"> " + city[key] +"</option>";
            }
            $("#cvilliage").html(str)
        })
    }
</script>